<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
	let socket;
	function openSocket() {
		const socketUrl = "ws://localhost:8088/api/pushMsg/"+ $("#userId").val();
		console.log(socketUrl);
		if (socket != null) {
			socket.close();
			socket = null;
		}
		socket = new WebSocket(socketUrl);
		//打开事件
		socket.onopen = function() {
			console.log("websocket已打开");
		};
		
		//获得消息事件
		socket.onmessage = function(msg) {
			console.log(msg.data);
			//发现消息进入,开始处理前端触发逻辑
		};
		//关闭事件
		socket.onclose = function() {
			console.log("websocket已关闭");
		};
		//发生了错误事件
		socket.onerror = function() {
			console.log("websocket发生了错误");
		}
	}
	function sendMessage() {
		socket.send('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
		
		console.log('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
	}
</script>
<body>
	<p>【socket开启者的ID信息】：
	<div>
		<input id="userId" name="userId" type="text" value="10">
	</div>
	<p>【客户端向服务器发送的内容】：
	<div>
		<input id="toUserId" name="toUserId" type="text" value="" placeholder="请输入用户id"> 
		<input id="contentText" name="contentText" type="text" value="" placeholder="请输入内容">
	</div>
	<p>【操作】：
	<div>
		<input type="button" onclick="openSocket()" value="开启socket">
	</div>
	<p>
	<div>
		<input type="button" onclick="sendMessage()" value="发送消息">
	</div>
</body>